# _*_ encoding: utf-8 _*_
try:
    import xml.etree.cElementTree as ET
except ImportError:
    import xml.etree.ElementTree as ET


def process_time(filename):
    data = []
    with open(filename, "rb") as f:
        for line in f:
            elems = line.strip().split(',')
            second = int(elems[0])
            hour = second / 3600
            minute = (second - hour * 3600) / 60
            second %= 60
            elems[0] = "{0}:{1}:{2}".format(hour, minute, second)
            data.append(elems)
    with open(filename, "wb") as f:
        for d in data:
            f.writelines(["{0},{1},{2}\n".format(d[0], d[1], d[2])])


# filename = "../../data/1108/ex8/11011607-1108.res.csv"
# process_time(filename)


def load_depart_csv(filename, hasHeader=True):
    vehicles = {}
    with open(filename, "rb") as f:
        for line in f:
            if hasHeader:
                hasHeader = False
                continue
            elems = line.strip().split(',')
            elems[1] = int(float(elems[1]))
            elems[2] = int(float(elems[2]))
            vehicles.setdefault(elems[0], elems[1])
    return vehicles


def analyse_depart(origin_file, new_file, result_file):
    origin_depart = load_depart_csv(origin_file)
    new_depart = load_depart_csv(new_file)
    time_pool = {}
    for v_id in new_depart:
        if v_id not in origin_depart:
            continue
        delay = new_depart[v_id] - origin_depart[v_id]
        delay /= 300
        time_pool.setdefault(delay, 0)
        time_pool[delay] += 1
    # return sorted(time_pool.iteritems(), key=lambda d: d[0], reverse=False)
    with open(result_file, "wb") as f:
        f.write("time(min),amount\n")
        for key, value in sorted(time_pool.iteritems(), key=lambda d:d[0], reverse=False):
            f.write("{0},{1}\n".format(key * 5, value))


def test_analyse_depart():
    origin_file = "../../data/1108/basic/11011607-basic.depart.csv"
    new_file = "../../data/1108/ex8/11011607-1108.depart.csv"
    # new_file = "../../data/1108/basic/11011607-simulation.depart.csv"
    result_file = "../../data/1108/ex8/compare_with_basic_depart.diff.csv"
    analyse_depart(origin_file, new_file, result_file)

test_analyse_depart()


def extract_depart_time(roufile, destfile):
    vechiles = {}
    for event, node in ET.iterparse(roufile):
        if event == 'end':
            if node.tag == "vehicle":
                vechiles.setdefault(node.attrib['id'], float(node.attrib['depart']))
    with open(destfile, "wb") as f:
        f.write("vehicleId,depart,arrival\n")
        for id in vechiles:
            f.write("{0},{1},-1\n".format(id, vechiles[id]))


def test_extract_depart_time():
    rou_file = "../../data/1108/11011607-t.rou.xml"
    dest_file = "../../data/1108/basic/11011607-basic.depart.csv"
    extract_depart_time(rou_file, dest_file)
